<template>
  <div class="login-container">
    <div class="background-layer"></div>
    <el-card class="login-card">
      <h2 class="title">欢迎登录</h2>
      <el-form
        :model="form"
        :rules="rules"
        ref="loginForm"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="account">
          <el-input
            v-model="form.account"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-button type="primary" native-type="submit" class="login-btn">
          立即登录
        </el-button>
      </el-form>
      <el-button type="text" @click="handleRegister"
        >没有账号？立即注册</el-button
      >
    </el-card>
  </div>
</template>
  
  <script setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import apiClient from "@/axios"; // 引入配置好的 axios 实例
import useAuthStore from "@/stores/auth";

const authStore = useAuthStore();

// 响应式数据
const form = reactive({
  account: "",
  password: "",
});

// 验证规则
const rules = reactive({
  account: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 3, max: 15, message: "长度在3到15个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    { min: 5, max: 18, message: "长度在5到18个字符", trigger: "blur" },
  ],
});

// 表单提交
const handleLogin = async () => {
  try {
    const response = await apiClient.post("/auth/login", form);
    if (response.data.code === 200) {
      // 更新认证状态
      await authStore.login(response.data.data);
      ElMessage.success("登录成功");
      if (form.account === "admin") {
        await router.push({ name: "Admin" });
      } else {
        router.push({ name: "Index" });
      }
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error("服务器异常，请稍后再试");
    console.error("登录错误:", error);
  }
};
// 注册
const handleRegister = () => {
  router.push({ name: "Register" });
};
</script>
  
  <style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.background-layer {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(120deg, #7f7fd5, #86a8e7, #91eae4);
  opacity: 0.8;
}

.login-card {
  width: 400px;
  padding: 30px;
  z-index: 1;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #2c3e50;
}

.login-btn {
  width: 100%;
  margin-top: 20px;
  font-size: 16px;
  letter-spacing: 2px;
}
</style>